package org.jeecg.modules.demo.mall.yxstorecoupongrant.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.demo.mall.entity.YxStoreCoupon;
import org.jeecg.modules.demo.mall.entity.YxStoreCouponGrant;
import org.jeecg.modules.demo.mall.entity.YxStoreCouponUser;
import org.jeecg.modules.demo.mall.yxstorecoupon.service.IYxStoreCouponService;
import org.jeecg.modules.demo.mall.yxstorecoupongrant.service.IYxStoreCouponGrantService;
import org.jeecg.modules.demo.mall.yxstorecouponuser.service.IYxStoreCouponUserService;
import org.jeecg.modules.demo.mall.yxuser.service.IYxUserService;
import org.jeecg.modules.demo.weixin.message.utils.MessageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;

/**
 * @Description: 平台优惠券发放
 * @Author: jeecg-boot
 * @Date: 2023-11-08
 * @Version: V1.0
 */
@Api(tags = "平台优惠券发放")
@RestController
@RequestMapping("/mall/yxstorecoupongrant/yxStoreCouponGrant")
@Slf4j
public class YxStoreCouponGrantController extends JeecgController<YxStoreCouponGrant, IYxStoreCouponGrantService> {
    @Autowired
    private IYxStoreCouponGrantService yxStoreCouponGrantService;
    @Autowired
    private IYxStoreCouponUserService yxStoreCouponUserService;
    @Autowired
    private IYxStoreCouponService yxStoreCouponService;
    @Autowired
    private IYxUserService yxUserService;

    /**
     * 分页列表查询
     *
     * @param yxStoreCouponGrant
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "平台优惠券发放-分页列表查询")
    @ApiOperation(value = "平台优惠券发放-分页列表查询", notes = "平台优惠券发放-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<YxStoreCouponGrant>> queryPageList(YxStoreCouponGrant yxStoreCouponGrant,
                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                           HttpServletRequest req) {
        QueryWrapper<YxStoreCouponGrant> queryWrapper = QueryGenerator.initQueryWrapper(yxStoreCouponGrant, req.getParameterMap());
        Page<YxStoreCouponGrant> page = new Page<YxStoreCouponGrant>(pageNo, pageSize);
        IPage<YxStoreCouponGrant> pageList = yxStoreCouponGrantService.page(page, queryWrapper);
//        if(CollectionUtils.isEmpty(pageList.getRecords())){
//            return Result.ok(pageList);
//        }
//        pageList.getRecords().forEach(yxStoreCouponGrant1 -> {
//            YxStoreCoupon storeCoupon = yxStoreCouponService.getById(yxStoreCouponGrant1.getCouponId());
//            if (storeCoupon!=null){
//                yxStoreCouponGrant1.setCouponName(storeCoupon.getTitle());
//            }
//        });
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param yxStoreCouponGrant
     * @return
     */
    @AutoLog(value = "平台优惠券发放-添加")
    @ApiOperation(value = "平台优惠券发放-添加", notes = "平台优惠券发放-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody YxStoreCouponGrant yxStoreCouponGrant) {
        YxStoreCoupon coupon = yxStoreCouponService.getById(yxStoreCouponGrant.getCouponId());
        if (coupon == null) {
            return Result.error("优惠券不存在");
        }
        //获取当前优惠券过期时间
//        Calendar calendar = Calendar.getInstance();
//        calendar.add(Calendar.DAY_OF_MONTH, coupon.getCouponTime());
        String[] userids = yxStoreCouponGrant.getUserIds().split(",");
        Arrays.stream(userids).forEach(item -> {
            String phone = yxUserService.queryPhone(Integer.valueOf(item));
            //添加用户优惠券记录
            int i;
            for (i = 1; i <= yxStoreCouponGrant.getNum(); i++) {
                YxStoreCouponUser yxStoreCouponUser = new YxStoreCouponUser();
                yxStoreCouponUser.setCid(yxStoreCouponGrant.getCouponId());
//                yxStoreCouponUser.setEndTime(calendar.getTime());
                if (coupon.getIsFixedDate().equals(1)) {
                    Date date = new Date();
                    if (date.compareTo(coupon.getStartTime()) >= 0) {
                        yxStoreCouponUser.setStartTime(date);
                    } else {
                        yxStoreCouponUser.setStartTime(coupon.getStartTime());
                    }
                    yxStoreCouponUser.setEndTime(coupon.getEndTime());
                }
                yxStoreCouponUser.setUid(Integer.valueOf(item));
                yxStoreCouponUser.setCouponPrice(coupon.getCouponPrice());
                yxStoreCouponUser.setCouponTitle(coupon.getTitle());
                yxStoreCouponUser.setCouponType(coupon.getCouponType());
                yxStoreCouponUser.setDiscountPrice(coupon.getDiscountPrice());
                yxStoreCouponUser.setUseMinPrice(coupon.getUseMinPrice());
//                yxStoreCouponUser.setNum(yxStoreCouponGrant.getNum());
                yxStoreCouponUserService.save(yxStoreCouponUser);
                if (StringUtils.isNotBlank(phone)){
                    try {
                        MessageUtils.noticeMessage(phone,yxStoreCouponGrant.getMessageContent());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }

        });
        yxStoreCouponGrant.setCouponTotal(yxStoreCouponGrant.getUids() * yxStoreCouponGrant.getNum());
        yxStoreCouponGrantService.save(yxStoreCouponGrant);

        //获取发放总数量
        int total = yxStoreCouponGrant.getNum() * yxStoreCouponGrant.getUids();
        if (coupon.getCouponNum() < total) {
            return Result.error("发放数量与优惠券数量有冲突");
        }
        //减少优惠券库存的数量
        coupon.setCouponNum(coupon.getCouponNum()-total);
        yxStoreCouponService.updateById(coupon);
        return Result.OK("添加成功！");
    }

//    /**
//     * 编辑
//     *
//     * @param yxStoreCouponGrant
//     * @return
//     */
//    @AutoLog(value = "平台优惠券发放-编辑")
//    @ApiOperation(value = "平台优惠券发放-编辑", notes = "平台优惠券发放-编辑")
//    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
//    public Result<String> edit(@RequestBody YxStoreCouponGrant yxStoreCouponGrant) {
//        yxStoreCouponGrantService.updateById(yxStoreCouponGrant);
//        return Result.OK("编辑成功!");
//    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "平台优惠券发放-通过id删除")
    @ApiOperation(value = "平台优惠券发放-通过id删除", notes = "平台优惠券发放-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        yxStoreCouponGrantService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "平台优惠券发放-批量删除")
    @ApiOperation(value = "平台优惠券发放-批量删除", notes = "平台优惠券发放-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.yxStoreCouponGrantService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "平台优惠券发放-通过id查询")
    @ApiOperation(value = "平台优惠券发放-通过id查询", notes = "平台优惠券发放-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<YxStoreCouponGrant> queryById(@RequestParam(name = "id", required = true) String id) {
        YxStoreCouponGrant yxStoreCouponGrant = yxStoreCouponGrantService.getById(id);
        if (yxStoreCouponGrant == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(yxStoreCouponGrant);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param yxStoreCouponGrant
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, YxStoreCouponGrant yxStoreCouponGrant) {
        return super.exportXls(request, yxStoreCouponGrant, YxStoreCouponGrant.class, "平台优惠券发放");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, YxStoreCouponGrant.class);
    }

}
